/**
 * http混入
 * 在有http请求的组件中
 * 可混入此部分
 * 后续发送请求
 * 可直接调用this.http
 * this.http的参数部分详解参见createHttpHelp
 * 默认http模式为单模块，若需要改为多模块，在自己组件内重新定义httpMode为'model'来覆盖mixins内的httpMode
 * 选项式写法参考Vue2官网
 * tsx写法混入示例：
 * import { mixins } from 'vue-class-component'
 * 
 * class A extends mixins(httpMixin) { ... }
 */

import Vue from 'vue'
import axios, { CancelTokenSource, CancelTokenStatic } from 'axios'
import { Component } from 'vue-property-decorator'
import { createHttpHelp } from 'assets/utils'

@Component
export default class HttpMixin extends Vue {
    public __source!: CancelTokenSource

    public promiseStatus: 'pending' | 'fulfilled' = 'fulfilled'

    public httpMode: 'model' | 'single' = 'single'

    public http!: HttpHelp

    public created () {
        this.createHttp()
    }

    public activated () {
        this.promiseStatus === 'fulfilled' && this.createHttp()
    }

    public beforeRouteLeave (to, from, next) {
        this.__source && this.__source.cancel()
        this.promiseStatus = 'fulfilled'
        next()
    }

    public createHttp () {
        let cancelToken: CancelTokenStatic = axios.CancelToken
        this.__source = cancelToken.source()
        this.http = createHttpHelp({
            token: this.__source.token,
            mode: this.httpMode
        })
        this.promiseStatus = 'pending'
    }
}
